<template>
  <div style="position: relative">
    <div v-if="id" v-show="!disabled" :id="id" />
    <div v-else v-show="!disabled" :id="id" />
    <div
        v-if="disabled"
        class="disabled"
        :style="{ height: height + 'px', overflow: 'auto' }"
        v-html="value"
    />
  </div>
</template>
<script setup>
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';

// 定义 props
const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  value: {
    type: String,
    default: "",
  },
  height: {
    type: Number,
    default: 375,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  charCounterMax: {
    type: Number,
    default: 10000,
  },
});

// 定义 emits
const emit = defineEmits(['change']);

// 定义响应式数据
const content = ref('');
const con = ref(props.value);
const editor = ref(null);

// 监听 content 变化并触发事件
watch(content, (val) => {
  emit('change', val);
});

// 监听外部传入的 value 变化
watch(() => props.value, (val) => {
  con.value = val;
  if (editor.value) {
    editor.value.html.set(val);
  }
});

// 组件挂载时的逻辑
onMounted(() => {
  con.value = props.value;

  // 定义 FroalaEditor 图标
  FroalaEditor.DefineIcon('fontFamily', {NAME: `<strong>字体</strong>`, template: 'text'});
  FroalaEditor.DefineIcon('fontSize', {NAME: `<strong>字号</strong>`, template: 'text'});
  FroalaEditor.DefineIcon('lineHeight', {NAME: `<strong>行高</strong>`, template: 'text'});
  FroalaEditor.DefineIcon('paragraphFormat', {NAME: `<strong>段落</strong>`, template: 'text'});
  FroalaEditor.DefineIcon('firstIndent', {NAME: 'indent', SVG_KEY: 'indent'});

  // 注册首行缩进命令
  FroalaEditor.RegisterCommand('firstIndent', {
    title: '首行缩进',
    focus: false,
    undo: true,
    refreshAfterCallback: false,
    callback: function () {
      let selection = editor.value.selection.get();
      if (selection && !selection.isCollapsed) {
        const range = editor.value.selection.blocks();
        if(range && range.length > 0){
          for (let i = 0; i < range.length; i++){
            range[i].style.textIndent = '2rem';
          }
        }
      } else {
        // 如果无法获取有效的选择范围，可以尝试应用到整个编辑器
        editor.value.format.applyStyle({ 'text-indent': '2rem' });
      }
    }
  });

  // 初始化 FroalaEditor
  editor.value = new FroalaEditor(
      `#${props.id}`,
      {
        language: "zh_cn",
        heightMin: props.height,
        heightMax: props.height,
        toolbarButtons: ['html', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript',
          'textColor', 'backgroundColor', 'paragraphFormat', 'fontFamily', 'fontSize', 'lineHeight',
          'align', 'firstIndent',
          'undo', 'redo', 'clearFormatting', 'selectAll', 'fullscreen', 'fixBorder'
        ],
        fontFamily: {
          "SimSun":"宋体",
          "SimHei":"黑体",
          "Microsoft-YaHei":"微软雅黑",
          "Microsoft JhengHei":"微软正黑体",
          "NSimSun":"新宋体",
          "FangSong":"仿宋",
          "DFKai-SB":"标楷体",
          "KaiTi":"楷体",
        },
        fontSize: ['8','9','10','12','14','16','18','24'],
        zIndex: 3000,
        charCounterMax: props.charCounterMax,
        imageUploadURL: "/oss-api/oss/files/rich-text-upload-file",
        imageUploadParams: { appCode: "003", roleType: "04", uploadType: "02" },
        videoUploadURL: "/oss-api/oss/files/rich-text-upload-file",
        videoUploadParams: { appCode: "003", roleType: "04", uploadType: "03" },
        videoMaxSize: 200 * 1024 * 1024,
        fileUploadURL: "/oss-api/oss/files/rich-text-upload-file",
        fileUploadParams: { appCode: "003", roleType: "04", uploadType: "01" },
        events: {
          "image.uploaded": function (response) {
            return response;
          },
          "image.error": function (error) {
            if (error.code === 0 || (error.code === '0')) {
              ElMessage.error("上传服务器出错");
            } else if (error.code === 1 || (error.code === '1')) {
              ElMessage.error("错误的上传链接");
            } else if (error.code === 2 || (error.code === '2')) {
              ElMessage.error("上传返回值没有数据");
            } else if (error.code === 3 || (error.code === '3')) {
              ElMessage.error("不支持上传的图片类型");
            } else if (error.code === 4 || (error.code === '4')) {
              ElMessage.error("解析返回值失败");
            } else if (error.code === 5 || (error.code === '5')) {
              ElMessage.error("图片超出限制大小");
            } else if (error.code === 6 || (error.code === '6')) {
              ElMessage.error("错误的图片类型");
            }
          },
          "file.uploaded": function (response) {
            return response;
          },
          contentChanged: function () {
            content.value = editor.value.html.get();
          },
        },
      },
      () => {
        editor.value.html.set(con.value);
      }
  );
});
</script>
<style>
#logo {
  display: none;
}
#italic-1 {
  display: none !important;
}
/*.fr-toolbar.fr-top {
  z-index: 10 !important;
}*/
</style>
<style lang="scss" scoped>
.disabled {
  width: 100%;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 10px;
  box-sizing: border-box;
  word-break: break-word;
  display: inline-block;
}
:deep(.disabled) img,
:deep(.disabled) table,
:deep(.disabled) tr,
:deep(.disabled) td {
  max-width: 100% !important;
}
:deep(.fr-box.fr-basic .fr-wrapper) {
  box-sizing: content-box;
}
:deep(.fr-box.fr-fullscreen){
  background-color: #fff;
}
:deep(.fr-code) {
  max-height: none !important;
}

:deep(.fr-table-selector-active) {
  opacity: 0;
}

:deep(.fr-box.fr-basic){
  z-index: auto !important;
}
:deep(.fr-box .second-toolbar){
  display: flex;
  background: #fff;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 10px 10px;
  .fr-counter{
    margin-left: auto;
    float: none;

  }

}
</style>
